// 导入校验插件
import wxValidate from 'wechat-validate'

Page({
  behaviors:[wxValidate],
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    name: '',
    gender: 1,
    mobile: '',
    houseInfo: '',
    visitDate: '',
    houseId:'',
    currentDate: Date.now(),
    maxDate: Date.now() + 1000 * 60 * 60 * 24 * 3,
  },
  rules:{
    name: [
      { required: true, message: '访问姓名不能为空' },
      { pattern:/^[\u4e00-\u9fa5]{2,5}$/, message: '访客姓名只能为中文' }
    ],
    mobile: [
      { required: true, message: '手机号码不能为空' },
      { pattern:/^1[3-9]\d{9}$/, message: '请填写正确的手机号' }
    ],
    houseId:[
      { required: true, message: '请选择到访房屋信息' }
    ],
    visitDate: [
      { required: true, message: '请选择到访时间日期' }
    ]
  },
  onLoad() {
    this.getHouseList()
  },
  // 获取房屋列表
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/house')
    if (code !== 10000) return wx.utils.toast('获取房屋列表数据失败')
    this.setData({
      houseList,
    })
  },
  // 获取用户的房屋信息
  selectHouseInfo(ev) {
    console.log(ev)
    // 记录获取的数据
    this.setData({ 
      houseInfo: ev.detail.name,
      houseId: ev.detail.id
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  selectDateInfo(ev) {
    // 记录获取时间并关闭弹层
    this.setData({
      visitDate: wx.utils.dataFormat(ev.detail),
      dateLayerVisible: false,
    })
    // console.log(ev)
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async goPassport() {
    // 校验数据
    if(!this.validate()) return wx.utils.toast('请填写完整信息')
    const { name, gender, mobile, visitDate, houseId } = this.data
    const {code, data:{id}} =await wx.http.post('/visitor', { name, gender, mobile, visitDate, houseId })
    // 检测接口是否调用成功
    if(code !== 10000) return wx.utils.toast('提交失败')
    // 跳转到页面
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id='+id,
    })
  },
})
